const dao = require('./base');

module.exports = {

    currencyList: function (condition, fields = "*", by = []) {
        let sql = `SELECT ${fields} from dd_currency where 1=1`;
        let pre = [];
        if (condition.id !== undefined && condition.id !== '') {
            sql += ` and a.id = ?`;
            pre.push(condition.id);
        }
        if (condition.addressHave !== undefined && condition.addressHave !== '') {
            sql += ` and contract_address != ''`;
        }
        sql = dao.by(sql, by);
        let limit = dao.limit(sql, condition, pre);
        sql = limit.sql;
        pre = limit.pre;
        return dao.query(sql, pre).then((results, fields) => {
            return results;
        }).catch((err) => {
            throw new Error(err + " sql：" + sql + " pre：" + pre);
        });
    },

    currencyAdd: function (fields = {}) {
        let sql = "INSERT INTO `ex_block` (`number`, `hash`, `parentHash`, `timestamp`, `nonce`, `difficulty`, `gasLimit`, `gasUsed`, `miner`, `extraData`, `transactions`, `transCount`) VALUES " +
            "(?,?,?,?,?,?,?,?,?,?,?,?)";
        let pre = [];
        pre.push(fields.number);
        pre.push(fields.hash);
        pre.push(fields.parentHash);
        pre.push(fields.timestamp);
        pre.push(fields.nonce);
        pre.push(fields.difficulty);
        pre.push(fields.gasLimit);
        pre.push(fields.gasUsed);
        pre.push(fields.miner);
        pre.push(fields.extraData);
        pre.push(fields.transactions);
        pre.push(fields.transCount);
        return dao.query(sql, pre).then((results, fields) => {
            return results;
        }).catch((err) => {
            throw new Error(err + " sql：" + sql + " pre：" + pre);
        });
    },

    currencyUpdate: async function (condition = {}, fields = {}) {
        let sql = "update dd_currency set ";
        let pre = [];
        if (fields.last_price !== undefined && fields.last_price !== '') {
            sql = dao.update_sql_splice(sql, "last_price");
            pre.push(fields.last_price);
        }
        if (condition.id !== undefined && condition.id !== '') {
            sql += ` where id = ?`;
            pre.push(condition.id);
        } else {
            throw new Error("condition is null");
        }

        return dao.query(sql, pre).then((results, fields) => {
            return results;
        }).catch((err) => {
            throw new Error(err);
        });
    },


};
